﻿using Microsoft.AspNetCore.Http.Metadata;
using SH.Common.CommonReturn;
using SH.Multitenant.Application.IServices.IEmpRole;
using SH.Multitenant.Domain.RBAC;
using SH.Multitenant.Infrastructure.IRepository;
using SH.Multitenant.Infrastructure.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SH.Multitenant.Application.Services
{
    public class EmpRoleServices : BaseServices<Emp_Role>, IEmpRoleServices
    {
        private readonly IEmpRoleRepository _employeeRoleRepository;
        //private readonly IEmpRepository _employeeRepository;
        public EmpRoleServices(IEmpRoleRepository repository, IEmpRepository employeeRepository) : base(repository)
        {
            _employeeRoleRepository = repository;
            //_employeeRepository = employeeRepository;
        }
        //员工角色修改
        public async Task<ApiResult<int>> EmpRoleUpdAsync(string empId, int roleId)
        {
            using var tran = _employeeRoleRepository.MultitenantUseTran();
            try
            {
                ApiResult<int> apiResult = new ApiResult<int>();
                var empRole = await _employeeRoleRepository.All.FirstAsync(x => x.EmpId == empId);
                if (empRole != null)
                {
                    empRole.RoleId = roleId;
                    _employeeRoleRepository.Upd(empRole);
                    apiResult.Success();
                }
                else
                {
                    //员工-角色表添加
                    var result = await _employeeRoleRepository.InsertAsync(new Emp_Role
                    {
                        EmpId = empId,
                        RoleId = roleId,
                    });
                    if (result > 0)
                    {
                        apiResult.Success();
                    }
                    else
                    {
                        tran.RollbackTran();
                        apiResult.Error(ApiResult<int>.ErrorType.Service, "员工角色修改失败");
                    }
                }
                tran.CommitTran();
                return apiResult;
            }
            catch (Exception)
            {
                tran.RollbackTran();
                throw;
            }

        }


    }
}
